package com.qingyun.pdfservice.controller;


import com.qingyun.common.dto.Result;
import com.qingyun.pdfservice.service.IPdfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


/**
 * PDF生成控制器
 */
@RestController
@Slf4j
public class PdfController {
    
    @Autowired
    private IPdfService pdfService;
    

    /**
     * 直接返回PDF二进制，供浏览器下载（更稳）
     */
    @GetMapping("/feedback/{feedbackId}/download")
    public ResponseEntity<Resource> downloadFeedbackPdf(@PathVariable Long feedbackId) {
        log.info("[PDF] /feedback/{}/download called", feedbackId);
        try {
            java.nio.file.Path target = java.nio.file.Path.of(
                    pdfService.getBaseUploadPath(), "pdf", "feedback_" + feedbackId + ".pdf");
            if (!java.nio.file.Files.exists(target)) {
                // 未生成完成，返回202，前端继续轮询
                return ResponseEntity.status(202).build();
            }
            byte[] bytes = java.nio.file.Files.readAllBytes(target);
            ByteArrayResource resource = new ByteArrayResource(bytes);
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=feedback_" + feedbackId + ".pdf");
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
            return ResponseEntity.ok().headers(headers).contentLength(bytes.length).contentType(MediaType.APPLICATION_PDF).body(resource);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }


    @PostMapping("/feedback/{feedbackId}/generate")
    public Result submitPdfTask(@PathVariable Long feedbackId) {
        return pdfService.submitPdfTask(feedbackId);
    }

}
